package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.mapper.RoleMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CrmRealm extends AuthorizingRealm{

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        //  调用父类的方法，并设置进去
        super.setCredentialsMatcher(credentialsMatcher);
    }

    //  提供认证信息的数据
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //  通过token获取用户名
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        //  通过用户名查询员工对象
        Employee employee = employeeMapper.checkName(username);
        //  若存在该对象
        if (employee != null) {
            //  返回四个参数
            //  用户名，用户真正的密码，加盐，当前数据源的名字
            return new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(employee.getName()), this.getName());
        }

        //  若不存在，则返回空
        return null;
    }

    //  提供授权信息的数据
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //  获取封装好的参数，进行强转
        Employee employee = (Employee)principalCollection.getPrimaryPrincipal();
        //  获取当前访问用户
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //  判断用户是否为超级管理员
        if (employee.isAdmin()) {
            //  若是，设置角色名称
            info.addRole("ADMIN");
            //  若是，设置权限表达式
            info.addStringPermission("*:*");
        } else {//  若不是
            //  根据id查询当前登录用户所有的角色名称
            List<String> roles = roleMapper.selectSnByEmpId(employee.getId());
            info.addRoles(roles);
            //  根据id查询当前登录用户所有的权限表达式
            List<String> list = permissionMapper.selectByEmpId(employee.getId());
            info.addStringPermissions(list);
        }

        //  返回当前用户
        return info;
    }

}
